#!/usr/bin/env python

import os
import pwd
import sys

from config import *
import server_listener

PID_FILE = '/var/run/qshftpd.pid'

if __name__ == '__main__':

    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    except OSError, err:
        print sys.stderr, "fork #1 failed: %d (%s)" %( err.errno, err.strerror)
        sys.exit(1)
    os.chdir('/')
    os.setsid()
    os.umask(022)
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    except OSError, err:
        print sys.stderr, "fork #2 failed: %d (%s)" % (err.errno, err.strerror)
        sys.exit(1)

    ftpd = server_listener.Listener(bindIP, bindPort)
    ftpd.start()
    
    pidfd = open(PID_FILE, 'w')
    pidfd.writelines(str(os.getpid()))
    pidfd.close()

    uid = pwd.getpwnam(run_as_user).pw_uid
    gid = pwd.getpwnam(run_as_group).pw_gid

    # for safety, we drop root privilege here
    os.setegid(gid)
    os.setuid(uid)
